package com.wonderful.compose.channel

import android.annotation.SuppressLint
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Button
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Scaffold
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Text
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Modifier
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.receiveAsFlow
import kotlinx.coroutines.launch

/**
 * Describe:
 *
 * @author Wonderful
 * @time 2025/9/9 16:23
 */
class SnackBarViewMode : ViewModel() {
    // 声明 Channel，用于传递 Snack bar 消息（String 类型为例）
    private val _snackBarChannel = Channel<String>()

    // 暴露为 Flow，方便界面侧收集（也可直接暴露 Channel，但 Flow 更符合 Jetpack 生态）
    val snackBarFlow = _snackBarChannel.receiveAsFlow()

    // 触发 Snack bar 事件的方法（可在任意异步逻辑后调用）
    fun triggerSnackBar(message: String) {
        viewModelScope.launch {
            _snackBarChannel.send(message)// 发送事件到 Channel
        }
    }
}

class ChannelDemo01Activity : ComponentActivity() {
    @SuppressLint("CoroutineCreationDuringComposition")
    @OptIn(ExperimentalMaterial3Api::class)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            val viewModel = SnackBarViewMode()
            val snackbarHostState = remember { SnackbarHostState() }
            val scope = rememberCoroutineScope()
            
            // 收集 Snack bar 事件流
            val message by viewModel.snackBarFlow.collectAsState(initial = "")

            Scaffold(
                snackbarHost = {
                    SnackbarHost(hostState = snackbarHostState)
                }
            ) { paddingValues ->
                Column(modifier = Modifier.padding(paddingValues)) {
                    // 模拟触发事件的按钮
                    Button(onClick = {
                        viewModel.triggerSnackBar("Success！") // 触发事件
                    }) {
                        Text(text = "Show Snack bar")
                    }
                }
            }

            // 监听消息变化并显示Snack bar
            if (message.isNotBlank()) {
                scope.launch {
                    snackbarHostState.showSnackbar(message)
                }
            }
        }
    }
}